/*
 * @description:
 * @author: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @Date: 2024-03-11 22:20:36
 * @FilePath: \dynamic-conf\fo\fileOpen.go
 * @LastEditTime: 2024-03-11 23:01:59
 * @LastEditors: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 */
package fo

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"

	log "github.com/sirupsen/logrus"
)

var sysType = runtime.GOOS

// OpenFile 判断文件是否存在  存在则OpenFile 不存在则Create
func OpenFile(filename string) (*os.File, error) {
	// 创建多级目录
	dir := GetDir(filename)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		log.Error(fmt.Sprintf("Error creating diretory for %s:%v", filename, err))
	}
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		log.Info(fmt.Sprintf("File %s not exists,do create it.", filename))
	}
	log.Info(fmt.Sprintf("File %s exists,open it.", filename))
	// 打开文件
	file, err := os.OpenFile(filename, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0o666)
	if err == nil {
		return file, nil
	}
	return nil, err
}

// 获取文件所在的目录路径
func GetDir(path string) string {
	// eg:  /data/prometheus/alter-config.yaml,basePath:alter-config.yaml
	basePath := filepath.Base(path)
	log.Debug(fmt.Sprintf("Path: %s base path: %s", path, basePath))
	return path[0 : len(path)-len(basePath)]
}

func GetOsPath(path string) string {
	if sysType == "linux" {
		// LINUX系统
		toPath := filepath.ToSlash(path)
		log.Info(fmt.Sprintf("Linux os convert path %s to %s.", path, toPath))
		return toPath
	}
	if sysType == "windows" {
		// windows系统
		toPath := filepath.FromSlash(path)
		log.Info(fmt.Sprintf("Windows os convert path %s to %s.", path, toPath))
		return toPath
	}
	return "."
}
